package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.VO.UserRoleIDS;
import com.itheima.VO.User_ids;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;


    //获得当前用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername() {
        //当 spring security 完成认证后,会将用户信息保存到上下文对象中 session
        //使用 spring security 提供的  org.springframework.security.core.userdetails.User
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null) {
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
        String username = user.getUsername();

        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
    }

    @PreAuthorize("hasAuthority('USER_QUERY')")
    @RequestMapping("/findAlluser")
    public PageResult findAllUser(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = userService.findAllUser(queryPageBean);
        return pageResult;
    }

    @PreAuthorize("hasAuthority('USER_ADD')")
    @RequestMapping("/addUser")
    public Result addUser(@RequestBody User_ids user_ids) {
        try {
            userService.addUser(user_ids);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
        return new Result(true, "新建用户成功");
    }

    @PreAuthorize("hasAuthority('ROLE_ADD')")
    @RequestMapping("/addUserRoleS")
    public Result addUserRoleS(@RequestBody UserRoleIDS userRoleIDS) {
        try {
            userService.addUserRoleS(userRoleIDS);
        } catch (RuntimeException e) {
           return new Result(false,e.getMessage());
        }
        return new Result(true,"添加用户角色成功");
    }

    @RequestMapping("/findAllUser")
    public Result findAllUser() {
        try {
            List<com.itheima.POJO.User> users = userService.findAllHealthManager();
            return new Result(true,"查询所有健康管理师成功",users);
        } catch (RuntimeException e) {
            return new Result(false,"查询所有健康管理师失败");
        }
    }
}
